import { uJob, obj_str, is_empty, d_sort, cline, uDb } from 'sui';

const reload_order = (hDone, setMain) => {
    uJob(hDone, "goods/order",
        {
            line: cline(),
            count: true,
        },
        r => {
            d_sort(r, "sn");

            r.forEach((d, i) => {
                d["index"] = i + 1;

                if (d.v) {
                    d["num"] = d.v.length;
                }
            });

            setMain(r);
        }, e => setMain(null));
};

const reload_psn = (hDone, setMain, cur) => {
    uJob(hDone, "goods/loadpsn",
        {
            line: cline(),
            k: obj_str(cur, "sn"),
        },
        data => {
            if (is_empty(data)) {
                setMain(null);
                return;
            }

            d_sort(data, "sn");

            data.forEach((d, i) => d["index"] = i + 1);

            setMain(data);
        }, e => setMain(null));
};

const do_del = (umd, cur, v, hcmd) => {
    umd.startWait();

    const sn = obj_str(cur, "sn");

    uDb(null, "file/get/gorder",
        {
            line: cline(),
            sn: sn,
        },
        r => {
            const val = r.v;
            const psn = obj_str(v, "sn");

            if (is_empty(val)) {
                umd.endWait();
                return;
            }

            const ret = val.filter(d => d !== psn);

            if (is_empty(ret)) {
                uDb(null, "file/rm/gorder",
                    {
                        line: cline(),
                        sn: sn,
                    },
                    r => hcmd(),
                    e => umd.setErr());
            } else {
                uDb(null, "file/md/gorder",
                    {
                        line: cline(),
                        sn: sn,
                        v: {
                            v: ret
                        }
                    },
                    r => hcmd(),
                    e => umd.setErr());
            }
        },
        e => umd.setErr());
};

export {do_del, reload_psn, reload_order};
